package com.youdianstar.app.ui.reward

import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.entity.CouponRes
import com.youdianstar.app.databinding.ActivityRewardHomeBinding
import com.youdianstar.app.entity.RedeemResult

import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.StrUtil


import com.youdianstar.app.common.network.BaseApiLsStateObserver
import com.youdianstar.app.common.network.model.DataState
import com.youdianstar.app.adapter.CouponHomeAdapter
import com.youdianstar.app.entity.PointAccount
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity

import com.youdianstar.app.common.auko.startActivity
import com.gyf.immersionbar.ImmersionBar
import com.safframework.eventbus.EventBus
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: RewardHomeActivity
 * Author: 82149 Create: 2022/2/16 9:58
 * Changes (from 2022/2/16)
 * --------------------------------------------------
 * description: 优惠券/优惠码 模块主入口
 * ---------------------------------------------------
 *
 */
class RewardHomeActivity : BaseActivity<ActivityRewardHomeBinding, RewardViewModel>() {
    override fun layoutId(): Int = R.layout.activity_reward_home

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): RewardViewModel {
        val model: RewardViewModel by viewModel()
        return model
    }

    //选中类型: 0-优惠券 1-优惠码
    private var selectType = 0
    private val couponList: MutableList<CouponRes> = mutableListOf()
    private var mListAdapter: CouponHomeAdapter? = null

    /*分页加载*/
    private var page = 0 //偏移量 0开始
    private var isRefresh: Boolean = true
    private var netSateCallback: NetStateCallback? = null

    //积分余额
    private var pointBalance = 0

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null && isShouldHideKeyBord(view, ev)) {
                this.hideSoftInput(view.windowToken)
                try {
                    mBinding.edtPromo.clearFocus()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun initViewLayout() {
        super.initViewLayout()
        ImmersionBar.with(this).keyboardEnable(true).init()
        mBinding.headBar.initTitle(this, title = getString(R.string.menu_coupon))
        selectType = intent.getIntExtra(Extra.IT_TYPE,0)

        mBinding.edtPromo.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                mBinding.btnRedeemR.isEnabled =
                    (s.toString().isNotEmpty() && s.toString().length >= 8)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
        mBinding.btnRedeemR.isEnabled = false
        if (selectType == 1)
            mBinding.rgCouponType.check(R.id.btn_promoCode_list)
        mBinding.rgCouponType.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(rg: RadioGroup?, checkedId: Int) {
                selectType = when (checkedId) {
                    R.id.btn_coupon_list -> 0
                    else -> {
                        1
                    }
                }
                refreshList()
            }
        })

        mBinding.smartRefresh.run {
            this.setOnRefreshListener {
                refreshList()
            }

            this.setOnLoadMoreListener {
                loadMoreData()
            }
        }

        mBinding.rcyCoupons.layoutManager = LinearLayoutManager(this)
        mListAdapter = CouponHomeAdapter(this, couponList)
        mBinding.rcyCoupons.adapter = mListAdapter

        netSateCallback = NetStateCallback(mBinding.rcyCoupons, false)
        EventBus.post(BusEntity(DataCode.CLOSE_DRAWER))//关闭侧边栏
    }

    override fun initData() {
        super.initData()
        //获取积分账户
        mViewModel.getPointAccount()
        //获取优惠券列表
        refreshList(true)
    }

    override fun onResume() {
        super.onResume()
        if (DataAppManager.instance.couponUpdateTag) {
            DataAppManager.instance.couponUpdateTag = false
            pointBalance = DataAppManager.instance.pointBalance
            refreshList(true)
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        //获取账户积分
        mViewModel.pointAccountLiveData.observe(this, object : BaseApiResultObserver<PointAccount>() {
                override fun onDataResult(data: PointAccount?) {
                    super.onDataResult(data)
                    data?.let {
                        pointBalance = it.point
                        DataAppManager.instance.pointBalance = it.point
                    }
                }
            })

        netSateCallback?.let { netCallback ->
            mViewModel.couponResLiveData.observe(this, netCallback)
        }

        mViewModel.redeemPromoResultData.observe(this, object : BaseApiResultObserver<RedeemResult>() {
                override fun onDataResult(data: RedeemResult?) {
                    super.onDataResult(data)
                    dismissDialog()
                    data?.let { res ->
                        toastShow(getString(R.string.public_success))
                        refreshList(true)
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    dismissDialog()
                    toastShow(e)
                }
            })
    }

    override fun initClickEvent() {
        mBinding.btnConfirm.setThrottleListener {
            //跳转 优惠券中心页面 (06/11 因为优惠券列表页与中心页对应不上了)
            startActivity<RedeemListActivity>(
                Extra.IT_TYPE to 0,
                Extra.IT_DATA to pointBalance
            )
        }

        mBinding.btnRedeemR.setThrottleListener {
            //优惠码兑换 接口
            val codeStr = mBinding.edtPromo.text.toString()
            if (StrUtil.isEmpty(codeStr)) {
                return@setThrottleListener
            }
            if (codeStr.length < 8) {
                toastShow(getString(R.string.toast_validPromo))
                return@setThrottleListener
            }
            mViewModel.redeemCouponWithPromo(codeStr)
        }
    }

    /*刷新列表*/
    private fun refreshList(isShow: Boolean = false) {
        isRefresh = true
        page = 0
        if (isShow)
            showLoadingDialog("")
        if (selectType == 0)
            mViewModel.getCouponsRecord(offset = page)
        else
            mViewModel.getPromoCodeRecord(offset = page)
    }

    /*加载更多*/
    private fun loadMoreData() {
        isRefresh = false
        page = couponList.size
        if (selectType == 0)
            mViewModel.getCouponsRecord(offset = page)
        else
            mViewModel.getPromoCodeRecord(offset = page)
    }

    /**更新列表布局数据*/
    fun updateListLayoutData(refresh: Boolean, netList: List<CouponRes>?) {
        if (refresh)
            couponList.clear()
        netList?.let {
            couponList.addAll(it)
        }
        mListAdapter?.notifyDataSetChanged()
    }

    /**回调网络接口*/
    private fun onNetResult(isError: Boolean) {
        if (isRefresh)
            mBinding.smartRefresh.finishRefresh()
        else
            mBinding.smartRefresh.finishLoadMore()
        if (couponList.isEmpty()) {
            netSateCallback?.showViewState(if (isError) DataState.STATE_ERROR else DataState.STATE_EMPTY)
        } else {
            netSateCallback?.showViewState(DataState.STATE_SUCCESS)
        }
        dismissDialog()
    }

    inner class NetStateCallback(view: View, autoNet: Boolean) :
        BaseApiLsStateObserver<List<CouponRes>>(view, autoNet) {
        override fun onReload(v: View?) {
            if (selectType == 0)
                mViewModel.getCouponsRecord(offset = page)
            else
                mViewModel.getPromoCodeRecord(offset = page)
        }

        override fun onDataResult(data: List<CouponRes>?) {
            data?.let { list ->
                list.forEach {
                    it.dataType = selectType
                }
                updateListLayoutData(isRefresh, list)
            }
            onNetResult(false)
        }

        override fun onDataEmpty() {
            super.onDataEmpty()
            updateListLayoutData(isRefresh, null)
            onNetResult(false)
        }

        override fun onNetError(code: Int, e: String?) {
            super.onNetError(code, e)
            onNetResult(code == -1)
        }
    }

}